package com.knife.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;
import java.lang.Process;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeConnectionProtocol;
import org.artofsolving.jodconverter.office.OfficeManager;

import com.knife.member.*;

import tools.ConvertVideo;

public class UpdateFile extends HttpServlet {

    private static final long serialVersionUID = -3983795918580954675L;
    String tpath = "/opt/user/netfs/";
    String webpath = "/user/netfs/";
    Boolean isConvert = false;
    DocumentDAO docDAO = new DocumentDAO();
    Document newDoc = new Document();

    /**
     * Constructor of the object.
     */
    public UpdateFile() {
        super();

    }

    /**
     * Destruction of the servlet. <br>
     */
    @Override
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here

    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to
     * post.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // response.setContentType("text/html");
        String realPath = "";
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        // ServletOutputStream out = response.getOutputStream();
        PrintWriter out = response.getWriter();
        if (ServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory dff = new DiskFileItemFactory();
            dff.setRepository(new File(tpath));
            ServletFileUpload sfu = new ServletFileUpload(dff);
            try {
                FileItemIterator fii = sfu.getItemIterator(request);
                while (fii.hasNext()) {
                    FileItemStream fis = fii.next();

                    if (fis.isFormField()) {
                        InputStream is = fis.openStream();
                        if (fis.getFieldName().equals("title")) {
                            newDoc.setTitle(Streams.asString(is));
                        } else if (fis.getFieldName().equals("username")) {
                            newDoc.setAuthor(Streams.asString(is));
                        } else if (fis.getFieldName().equals("type")) {
                            newDoc.setDocumenttype(Streams.asString(is));
                        } else if (fis.getFieldName().equals("risktype")) {
                            newDoc.setRisktype(Streams.asString(is));
                        } else if (fis.getFieldName().equals("source")) {
                            newDoc.setSource(Streams.asString(is));
                        } else if (fis.getFieldName().equals("isfee")) {
                            newDoc.setIsfee(Boolean.parseBoolean(Streams.asString(is)));
                        }
                    } else if (!fis.isFormField() && fis.getName().length() > 0) {
                        BufferedInputStream in = new BufferedInputStream(
                                fis.openStream());
                        String ext = FilenameUtils.getExtension(fis.getName());
                        UUID uid = UUID.randomUUID();
                        String localfilename = tpath + uid.toString() + "." + ext;
                        BufferedOutputStream outfile = new BufferedOutputStream(
                                new FileOutputStream(new File(localfilename)));
                        Streams.copy(in, outfile, true);
                        outfile.close();
                        realPath = processConvert(localfilename);
                        File ufile = new File(localfilename);
                        ufile.delete();
                        File filepdf = new File(tpath + FilenameUtils.getBaseName(localfilename) + ".pdf");
                        filepdf.delete();
                    }
                }
            } catch (Exception e) {
            	e.printStackTrace();
            }
            if (isConvert) {
                newDoc.setFileurl(realPath);
                Timestamp applyTime = new Timestamp((new Date()).getTime());
                newDoc.setDate(applyTime);
                docDAO.save(newDoc);
                out.println("<script language=\"javascript\">alert('添加成功！');location.href='/user/admin/inc/dataadd.jsp';</script>");
                out.close();
            } else {
                out.println("<script language=\"javascript\">alert('转换失败！请上传正确格式的文件');history.back(-1);</script>");
                out.close();
            }
        }
        /*
         * try { request.getRequestDispatcher("admin/inc/dataadd.jsp").forward(
         * request, response); } catch (Exception e) { }
         */
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException
     *             if an error occurs
     */
    @Override
    public void init() throws ServletException {
        // Put your code here
        super.init();
        try {
        } catch (Exception e) {
        }

    }

    private String processConvert(String filename) throws IOException,
            InterruptedException {

        String transfername = filename;
        // System.out.println(filename);

        String realPath = "";
        if (filename.length() > 0
                && fileext(filename)
                && (isText(filename) || isPDF(filename) || isPPT(filename)
                || isDoc(filename) || isExcel(filename))) {
            if (isText(filename)) {
                // 文件类型:文本、PPT、视频、音频、PDF
                newDoc.setFiletype("文本");
                transfername = transTxt(filename);
            } else if (isPDF(filename)) {
                newDoc.setFiletype("PDF");
            } else if (isPPT(filename)) {
                newDoc.setFiletype("PPT");
            } else if (isDoc(filename)) {
                newDoc.setFiletype("DOC");
            } else if (isExcel(filename)) {
                newDoc.setFiletype("EXCEL");
            }
            String pdf = filename;
            if (!isPDF(filename)) {
                pdf = convertPDF(transfername);
            }

            realPath = convertPDFtoSwf(pdf);

        } else if (isVideo(filename) || isAudio(filename)) {
            if (isVideo(filename)) {
                newDoc.setFiletype("视频");
            } else if (isAudio(filename)) {
                newDoc.setFiletype("音频");
            }
            realPath = convertVideotoFlv(filename);
        }

        return realPath;

    }

    private String convertPDFtoSwf(String pdf) throws IOException,
            InterruptedException {

        String[] command = new String[]{
            "/bin/sh",
            "-c",
            "pdf2swf  " + pdf + "  -o " + tpath + getBasicName(pdf)
            + ".swf"};

        Process proc = Runtime.getRuntime().exec(command);
        proc.waitFor();
        isConvert = true;

        return webpath + getBasicName(pdf) + ".swf";

    }

    private String convertVideotoFlv(String filename) {
        ConvertVideo.convertToFLV("ffmpeg", filename, tpath
                + getBasicName(filename) + ".flv", tpath
                + getBasicName(filename) + ".jpg");
        isConvert = true;
        return webpath + getBasicName(filename) + ".flv";
    }

    private String getBasicName(String filename) {
        File regularfile = new File(filename);
        return regularfile.getName().substring(0,
                regularfile.getName().indexOf("."));

    }

    private boolean isExcel(String filename) {
        File regularfile = new File(filename);
        if (regularfile.getName().indexOf(".xls") > -1) {
            return true;
        }
        return false;
    }

    private boolean isDoc(String filename) {
        File regularfile = new File(filename);
        if (regularfile.getName().indexOf(".doc") > -1) {
            return true;
        }
        return false;
    }

    private boolean isPPT(String filename) {
        File pptfile = new File(filename);
        if (pptfile.getName().indexOf(".ppt") > -1) {
            return true;
        }
        return false;
    }

    private boolean isPDF(String filename) {
        File pdffile = new File(filename);
        if (pdffile.getName().indexOf(".pdf") > -1) {
            return true;
        }
        return false;
    }

    private boolean fileext(String filename) {
        File regularfile = new File(filename);

        if (regularfile.getName().length() > 0) {
            return true;
        }
        return false;
    }

    private boolean isText(String filename) {
        File pdffile = new File(filename);
        if (pdffile.getName().indexOf(".txt") > -1) {
            return true;
        }
        return false;
    }

    private boolean isAudio(String filename) {
        File pdffile = new File(filename);
        if (pdffile.getName().indexOf(".mp3") > -1
                || pdffile.getName().indexOf(".mp4") > -1) {
            return true;
        }
        return false;
    }

    private boolean isVideo(String filename) {
        File pdffile = new File(filename);
        if (pdffile.getName().indexOf(".asf") > -1
                || pdffile.getName().indexOf(".wmv") > -1) {
            return true;
        }
        return false;
    }

    private String transTxt(String filename) {
        File regularfile = new File(filename);
        regularfile.renameTo(new File(tpath + getBasicName(filename) + ".odt"));
        return tpath + getBasicName(filename) + ".odt";
    }

    private String convertPDF(String transfername) {

        OfficeManager configuration = new DefaultOfficeManagerConfiguration().setConnectionProtocol(OfficeConnectionProtocol.SOCKET).buildOfficeManager();
        File output = new File(tpath + getBasicName(transfername) + ".pdf");
        System.out.println(tpath + getBasicName(transfername) + ".pdf");
        try {

            configuration.start();
            OfficeDocumentConverter documentConverter = new OfficeDocumentConverter(
                    configuration);
            documentConverter.convert(new File(transfername), output);

        } catch (Exception e) {
            return null;
        } finally {
            configuration.stop();
        }
        return tpath + getBasicName(transfername) + ".pdf";
    }
}
